<?php

namespace Admin\Controller;

use Admin\Builder\AdminListBuilder;
use Admin\Builder\AdminConfigBuilder;


class RcardController extends AdminController
{
    protected $rcardTypeModel;///
    protected $rcardModel;//
    protected $inviteModel;
    protected $inviteBuyLogModel;
    protected $inviteLogModel;
    protected $inviteUserInfoModel;
    protected $inviteTypeModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->inviteModel=D('Ucenter/Invite');
        $this->rcardModel=D('Rcard/Rcard');//
        $this->inviteTypeModel=D('Ucenter/InviteType');
        $this->rcardTypeModel=D('Rcard/RcardType');//
        $this->inviteBuyLogModel=D('Ucenter/InviteBuyLog');
        $this->inviteLogModel=D('Ucenter/InviteLog');
        $this->inviteUserInfoModel=D('Ucenter/InviteUserInfo');
    }




    public function RcardType($page=1,$r=20)
    {


        list($list,$totalCount)=$this->rcardModel->getList($map=array(),$page,$r);


        unset($val);


        $builder=new AdminListBuilder();
        $builder->title(L('_SECRET_TYPE_MANAGEMENT_'))
            ->buttonNew(U('Rcard/add'))
            ->setSelectPostUrl(U('Invite/invite'))
            /*->buttonDelete(U('Invite/delete'))*/
            ->setStatusUrl(U('setRcardTypeStatus')) ->buttonEnable()->buttonDisable()->buttonDelete()

            ->keyId()
            ->keyText('title',L('_TITLE_'))
            ->keyText('action',L('_INTEGRAL_SETTING_'))
            ->keyText('rcardlen',L('_CLOUD_CODE_LENGTH_'))
            ->setStatusUrl(U('setRcardTypeStatus'))
            -> keyStatus()
            ->keyDoActionEdit('add?id=###')
            ->keyCreateTime()
            ->data($list)
            ->pagination($totalCount,$r)
            ->display();
    }

    public function setRcardTypeStatus()
    {
        $ids = I('ids');
        $status = I('get.status', 0, 'intval');
        $builder = new AdminListBuilder();
        if ($status == 1) {
            foreach ($ids as $id) {
                $content = D('RcardType')->where(array('id'=>$id))->find();

          /*      D('Common/Message')->sendMessage($content['uid'],$title = L('_ALBUM_CONTENT_AUDIT_NOTICE_'), "管理员审核通过了您发布的内容。现在可以在列表看到该内容了。",  'Issue/Index/issueContentDetail', array('id' => $id), is_login(), 2);*/
                /*同步微博*/
                /*  $user = query_user(array('nickname', 'space_link'), $content['uid']);
                  $weibo_content = '管理员审核通过了@' . $user['nickname'] . ' 的内容：【' . $content['title'] . '】，快去看看吧：' ."http://$_SERVER[HTTP_HOST]" .U('Issue/Index/issueContentDetail',array('id'=>$content['id']));
                  $model = D('Weibo/Weibo');
                  $model->addWeibo(is_login(), $weibo_content);*/
                /*同步微博end*/

            }

        }
        $builder->doSetStatus('RcardType', $ids, $status);

    }
    public function setRcardStatus()
    {
        if($_POST){
            $ids = I('post.ids', "", 'intval');
        }else{
            $ids = I('get.id', "", 'intval');
        }

        $status = I('get.status', 0, 'intval');

        $builder = new AdminListBuilder();
        if ($status == 1) {
            foreach ($ids as $id) {
                $content = D('RcardType')->where(array('id'=>$id))->find();

                /*      D('Common/Message')->sendMessage($content['uid'],$title = L('_ALBUM_CONTENT_AUDIT_NOTICE_'), "管理员审核通过了您发布的内容。现在可以在列表看到该内容了。",  'Issue/Index/issueContentDetail', array('id' => $id), is_login(), 2);*/
                /*同步微博*/
                /*  $user = query_user(array('nickname', 'space_link'), $content['uid']);
                  $weibo_content = '管理员审核通过了@' . $user['nickname'] . ' 的内容：【' . $content['title'] . '】，快去看看吧：' ."http://$_SERVER[HTTP_HOST]" .U('Issue/Index/issueContentDetail',array('id'=>$content['id']));
                  $model = D('Weibo/Weibo');
                  $model->addWeibo(is_login(), $weibo_content);*/
                /*同步微博end*/

            }

        }
        $builder->doSetStatus('Rcard', $ids, $status);

    }


    public function add()
    {
        $aId = I('get.id', 0, 'intval');
        $is_edit = $aId ? 1 : 0;
        $title = $is_edit ? L('_EDIT_') : L('_NEW_');
        if (IS_POST) {
            $data['title'] = I('post.title', '', 'op_t');
            $data['rcardlen'] = I('post.rcardlen', 0, 'intval');
            $data['action'] = I('post.RE_FIELD', 0, 'op_t');
            $data['status'] = I('post.status', 0, 'intval');
            $data['create_time']=time();

            if ($is_edit) {
                $data['id'] = $aId;
                $result =$this->rcardTypeModel->saveData($data);
            } else {
                $result =$this->rcardTypeModel->addData($data);
            }
            if ($result) {
                $this->success($title . L('_SECRET_TYPE_OF_SUCCESS_WITH_EXCLAMATION_'), U('rcard/rcardtype'));
            } else {
                $this->error($title . L('_SECRET_TYPE_FAILURE_WITH_EXCLAMATION_') . $this->inviteTypeModel->getError());
            }
        } else {
            if($aId){
                $map['id']=$aId;
                $data= $this->rcardTypeModel->getData($map);
                $data['data']=json_decode( $data['action'],true);
                //dump($data);exit;

            }
            $field = D('Ucenter/Score')->getTypeList(array('status' => 1));

            $builder = new AdminConfigBuilder();

            $param = array();
            $param['opt'] = $field;
            $param['data']=$data['data'];
            $builder->title($title . L('_THE_SECRET_TYPE_'));
            $builder->keyTitle()->keyText('rcardlen', L('_THE_SECRET_LENGTH_'))
                ->keyUserDefined('RE_FIELD', L('_INTEGRAL_TYPE_'),'', T('Rcard@Rcard/config'), $param)
                ->keyStatus()
                ->buttonSubmit()->buttonBack()
                ->data($data)
                ->keyDefault('status',1)
                ->display();
        }
    }


    public function CreateRcard($page=1,$r=20)
    {

        $aStatus=I('status',1,'intval');

        $map['status']=array('eq',$aStatus);
        list($list,$totalCount)=$this->rcardModel->getRcardList($map,$page,$r);
        $typeOptions=$this->_getTypeList();
        foreach($typeOptions as &$val){
            $val['value']=$val['title'];
        }
        unset($val);
        $typeOptions=array_merge(array(array('id'=>0,'value'=>L('_ALL_'))),$typeOptions);

            $this->assign('rcard_list',$list);
             $this->assign('status',$aStatus);
            $this->assign('type_list',$typeOptions);

            //生成翻页HTML代码
            C('VAR_PAGE', 'page');
            $pager = new \Think\Page($totalCount, $r, $_REQUEST);
            $pager->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $paginationHtml = $pager->show();
            $this->assign('pagination', $paginationHtml);
            $this->display(T('Rcard@Rcard/creatercard'));


    }
    private function _getTypeList(){
        $map['status']=1;
        $type_list=$this->rcardTypeModel->getSimpleList($map);
        return $type_list;
    }

    public function createCode()
    {
        if(IS_POST){
            $data['rcard_type']=I('post.invite',0,'intval');
            $data['num']=I('post.rcard_number',0,'op_t');
                $result=  $this->rcardModel->createCodeAdmin($data);
            $this->ajaxReturn($result);
        }else{
            $type_list=$this->_getTypeList();
            $this->assign('type_list',$type_list);
            $this->display( T('Rcard@Rcard/create'));
        }
    }


    public function record($page=1,$r=20)
    {
        $list=D('RcardRecord')->page($page,$r)->select();
        $totalCount=D('RcardRecord')->count();
        unset($val);

        $builder=new AdminListBuilder();
        $builder->title(L('_SECRET_EXCHANGE_RECORD_'))
            ->keyId()
            ->keyUid('uid',L('_EXCHANGE_MAN_'))
            ->keyText('rcard_type',L('_SECRET_TYPE_NAME_'))
            ->keyText('action',L('_THE_SECRET_BEHAVIOR_'))
            ->keyText('code',L('_THE_SECRET_'))
            ->keyCreateTime()
            ->data($list)
            ->pagination($totalCount,$r)
            ->display();
    }



    public function cvs()
    {
        $aIds=I('ids',array());

        $map['id']=array('in',$aIds);

        $dataList=$this->rcardModel->getRcardList($map,'status desc,end_time desc');

        if(!count($dataList['0'])){
            $this->error(L('_NO_DATA_WITH_EXCLAMATION_'));
        }

        $data="id,卡密,标题,积分变动,生成时间,当前状态\n";
       // dump($dataList['0']);exit;
        foreach ($dataList['0'] as $val) {

            $val['create_time']=time_format($val['create_time']);
            $data.=$val['id'].",".$val['code'].",".$val['title'].",".$val['action'].",".$val['create_time'].",".$val['status']."\n";
        }
        $data=iconv('utf-8','gb2312',$data);
        $filename = date('Ymd').'.csv'; //设置文件名
        $this->export_csv($filename,$data); //导出
    }

    private function export_csv($filename,$data) {
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        header("Content-type:application/vnd.ms-excel;charset=utf-8");
        echo $data;
    }
}